package com.shoppingmall.handler;

import com.alibaba.fastjson.JSONObject;

import com.shoppingmall.commons.CurUser;
import com.shoppingmall.commons.Result;
import com.shoppingmall.model.UserInfo;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        System.out.println("用户认证信息...");

        User user = (User)authentication.getPrincipal();

        UserInfo userInfo = JSONObject.parseObject(user.getUsername(),UserInfo.class);

        CurUser curUser = new CurUser();
        curUser.setUser_id(userInfo.getUser_id());
        curUser.setUser_name(userInfo.getUser_name());

        request.getSession().setAttribute("curUser",curUser);
        //将curUser对象封装到Result对象中
        Result result = Result.success("登录成功",curUser);

        //设置响应类型及编码集
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(JSONObject.toJSON(result));
    }
}
